﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading;
using Microsoft.Phone.Scheduler;

namespace WP7_HackerTyper {
    public partial class TerminalPage : PhoneApplicationPage {
        private string shellCode;
        private string ipAddress;
        private int index;
        private byte speed;

        public TerminalPage() {
            InitializeComponent();

            // Reads HackScript.txt and sets shellCode content
            var resource = System.Windows.Application.GetResourceStream(new Uri("HackScript.txt", UriKind.Relative));
            StreamReader streamReader = new StreamReader(resource.Stream);
            shellCode = streamReader.ReadToEnd();
            index = 0;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
            base.OnNavigatedTo(e);

            // Gets and sets Speed if exists
            string tmp;
            if (NavigationContext.QueryString.TryGetValue("speed", out tmp)) {
                if (!byte.TryParse(tmp, out speed)) {
                    speed = 2;
                }
            }
            else {
                speed = 2;
            }

            if(NavigationContext.QueryString.TryGetValue("ipadr", out tmp)) {
                ipAddress = tmp;
            }
        }

        private void txtShell_KeyDown(object sender, KeyEventArgs e) {
            e.Handled = true;
            if (index < shellCode.Length) {
                for (int i = 0; i < speed; i++) {
                    AppendCharacter();
                }
            }
            else {
                txtTerminal.IsEnabled = false;
                btnHack.Visibility = System.Windows.Visibility.Visible;
                btnHack.Focus();
            }
        }

        private void AppendCharacter() {
            // Assume: index < shellCode.Length
            txtTerminal.Text += shellCode[index];
            index++;
            txtTerminal.SelectionStart = txtTerminal.Text.Length - 1;
            txtTerminal.SelectionLength = 0;
        }

        private void btnHack_Click(object sender, RoutedEventArgs e) {
            grdUploading.Visibility = Visibility.Visible;
            lblTarget.Text = string.Format(lblTarget.Text, ipAddress);

            Storyboard sb = Resources["LoadingStoryboard"] as Storyboard;
            sb.Begin();
            Thread x = new Thread(() => {
                Thread.Sleep(5000);
                Dispatcher.BeginInvoke(() => {
                    sb.Stop();

                    string result, message;
                    if ((DateTime.Now.Millisecond & 1) == 0) {
                        lblResult.Foreground = new SolidColorBrush(Color.FromArgb(0xff, 0x0, 0xff, 0x0));
                        result = "[ACCESS GRANTED]";
                        message = "Your code has been uploaded successfully!";

                        AddFakeAlarm("FBI detected your code, GTFO!!!!");
                    }
                    else {
                        lblResult.Foreground = new SolidColorBrush(Colors.Red);
                        result = "[ACCESS DENIED]";
                        message = "Push back button and try again.";
                    }

                    lblResult.Text = result;
                    MessageBox.Show(message);

                    lblResult.Visibility = System.Windows.Visibility.Visible;
                    btnHack.IsEnabled = false;
                });
            });
            x.Start();
        }

        private void AddFakeAlarm(string alarmMessage) {
            Alarm alarm = new Alarm(Guid.NewGuid().ToString());
            alarm.Content = alarmMessage;
            alarm.BeginTime = DateTime.Now.AddSeconds(20);
            alarm.Sound = new Uri("sounds/crap.wav", UriKind.Relative);

            ScheduledActionService.Add(alarm);
        }
    }
}
